
    let express = require("express")

    let router = express.Router()

    // 加载数据库
    let mysql = require("mysql")

        // 渲染数据库内容
        let config = {
            host:"localhost",//数据库连接地址
            port:3306,//数据库连接端口
            user:"root",//数据库用户名
            password:"root",//数据库密码
            database:"student_user",//选择要操作的库房
        }    

    // 连接数据库
    let connection =mysql.createConnection(config)
    // 渲染首页页面
    router.get("/index", (req, res) => { 
    // 渲染数据库内容到前端
        let sql = `select *from student`
        connection.query(sql, (err,doc) => { 
        if (err) {
            console.log("失败");
        } else { 
            console.log(doc);
            res.render("index.html", {doc:doc})
        }
    })
    })

    // 实现删除功能
    router.get("/del", (req, res) => { 
        let id = req.query.id
        // console.log(id);
        let sql = `delete from student where id=${id}`;
        connection.query(sql, (err) => { 
            if (err) {
                res.render("wait.html", {
                    wait: 2,
                    content: "删除失败",
                    href: "/index"
                })
            } else {
                res.render("wait.html", {
                    wait: 2,
                    content: "删除成功",
                    href: "/index"
                })
            }
        })
    })

    // 修改功能
    router.get("/update", (req, res) => { 
        let id=req.query.id
        let sql = `select * from student where id=${id}`   
        connection.query(sql, (err, result) => {
            if (err) {
                res.redirect("/index")
            } else { 
                res.render("edit.html", {result:result})
            }
        })
    })

    // 提交表单数据
    //处理数据
    router.post("/update", (req, res) => {
    //获取文本框输入的值
    let { name, sex, age, id } = req.body;
    //console.log(id, 11111);
    let sql = `update student set 姓名="${name}",性别="${sex}",年龄=${age} where id=${id}`;
    //执行sql语句
    connection.query(sql, (err, result) => {
        if (err) {
            res.render("wait.html", {
                wait: 2,//等待2秒
                content: "修改失败",//提示内容
                href: "/update",//跳转路由  
            })
        } else {
            //console.log(result);
            res.render("wait.html", {
                wait: 2,//等待2秒
                content: "修改成功",//提示内容
                href: "/index",//跳转路由  
            })
        }
    })

})

// 暴露
module.exports = router;